package com.ssl.basics.thread.incre;

import java.util.concurrent.CountDownLatch;

/**
 * 描述：多线程下，对同一个值进行自增操作，会得不到预期的结果
 *
 * @author ssl
 * @create 2021/7/13 0013.
 */
public class ThreadIncreDemo {
    static class ValueEntity {
        private int sum;

        public void incre() {
            sum++;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        int threadSize = 10;
        ValueEntity entity = new ValueEntity();
        CountDownLatch latch = new CountDownLatch(threadSize);
        for (int i = 0; i < threadSize; i++) {
            new Thread(() -> {
                for (int j = 0; j < 10000; j++) {
                    entity.incre();
                }
                latch.countDown();
            }, String.valueOf(i)).start();
        }
        latch.await();
        System.out.println(entity.sum);
    }
}
